package apof.util.xml
{
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.display.Loader;
	import flash.events.Event;
	import mx.collections.ArrayCollection;
	import flash.events.EventDispatcher;
	import mx.utils.ObjectProxy;
	import mx.managers.CursorManager;
	import mx.controls.Alert;
	import flash.events.IOErrorEvent;
	
	public class TransitionsGetter extends EventDispatcher
	{
		[Bindable]
		public var transitions:ArrayCollection;
		[Bindable]
		public var transitionsXml:XML;
		
		//username="abcx" type="user"
		public function TransitionsGetter(userName:String,type:String):void	{
//			CursorManager.setBusyCursor();
			
			var urlSrc:String;
			if(type=="friends")
				urlSrc="http://api.fanfou.com/statuses/friends_timeline.xml?id="+userName+"&count=20";
			else if(type=="user")
				urlSrc="http://api.fanfou.com/statuses/user_timeline.xml?id="+userName+"&count=20";
			else if(type=="around")
				urlSrc="http://api.fanfou.com/statuses/public_timeline.xml";
			
			trace("start getting transactions, type="+type+" ID:"+userName);
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(IOErrorEvent.IO_ERROR,ioErr);
			loader.addEventListener(Event.COMPLETE,request);
			loader.load(new URLRequest(urlSrc));
		}
		
		private function ioErr(e:Event):void{
//			CursorManager.removeAllCursors()
            Alert.show("网络传输错误","错误信息",4,null);
        }
		public function request(e:Event):void{
			var xml:XML = new XML(e.currentTarget.data);
//			xml = new XML(xml.child("statuses").toXMLString());
//			xml = xml.statuses.to;
			transitionsXml = xml;
			var array:Array = new Array;
			
			trace("transactions getting completed");
			
			for(var i:int=0; i<xml.child("status").length(); i++) {
//				var fid:String=friendsXml.user[i].child("name").toString();
//				var imgSrc:String = xml.item[i].child("title").toString();
				var name:String = xml.status[i].user.screen_name;
				var text:String = xml.status[i].text;
				var time:String = xml.status[i].created_at;
				var imgUrl:String = xml.status[i].user.profile_image_url;
				array.push({name:name,text:text,time:time,imgUrl:imgUrl});
				
			}
			transitions = new ArrayCollection(array);
			applyObjectProxy(transitions);
			
//			CursorManager.removeBusyCursor();
			
			this.dispatchEvent(new Event(Event.COMPLETE));
			
		}
		
		public function applyObjectProxy(targetAC:ArrayCollection):ArrayCollection
		{
			for(var i:String in targetAC)
			{targetAC[i] = new ObjectProxy(targetAC[i]);}
			return targetAC;
		}
		
		
		public function getTransitions():ArrayCollection {
			return transitions;
		}
		
		public function getTransitionsXml():XML{
			return transitionsXml;
		}
		
		
	}
}